package ncc.bs.Plugins;

import java.text.SimpleDateFormat;
import java.util.*;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import nc.bs.dao.BaseDAO;
import nc.bs.framework.common.NCLocator;
import nc.itf.pub.dbservice.IDBService;
import nc.jdbc.framework.generator.IdGenerator;
import nc.jdbc.framework.processor.MapListProcessor;
import nc.vo.bcbd.abstractmaterial.AbstractMaterialVO;
import nc.vo.bcbd.bcengine.BDBarCodeParseVO;
import nc.vo.pub.BusinessException;
import nccloud.bs.log.LogVO;
import nccloud.utils.baseapp.HttpReqUtils;
import nccloud.utils.baseapp.InitParamUtils;
import nccloud.utils.baseapp.ToolUtils;
import org.apache.poi.ss.formula.functions.T;

/**
 * <p>同步财政系统</p>
  * 单位会计现金流量表
 * @author Administrator
 * @date 2024年03月05日
 */
public class DWKJXJLLWriteBackgroundWorkPlugin extends AbstractBackgroundWorkPlugin {
	private BaseDAO dao;
	private final SimpleDateFormat ymd = new SimpleDateFormat("yyyy-MM-dd");
	private final SimpleDateFormat ymdsfm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private IDBService dbService;
	
	@SuppressWarnings("rawtypes")
	@Override
	public void doBusiness(Map keyMap) throws BusinessException {
		List<Map<String, Object>> lists = queryData(buildSQL(keyMap));
		try {
			List<List<Map<String,Object>>> listparams = super.getGroupAfterData(lists);
			if(listparams == null ) return;
			// 对分组的数据进行推送
			for(List<Map<String, Object>> params : listparams) {
				List<LogVO> listVOs = new ArrayList<>();
				String message = null;
				String issuccess = "Y";
				String result = null;
				try {
					String param = super.getParam(buildParam(params,listVOs),"DWKJHS08", super.getAppid()); // 每十行数据合并在一起推送
					if(param == null || "".equals(param)) return;
					result = HttpReqUtils.sendPost(getURL("DEF001"), param);
					getLog().info("----第四步接口响应结果::" + result);
					JSONObject jsonres = JSONObject.parseObject(result);
					Object code = jsonres.get("code");
					if("200".equals(code)) {
						message = "同步成功";
					}else {
						message = jsonres.getString("msg");
						issuccess = "N";
						result = jsonres.toString();
					}
					
				}catch(Exception e) {
					message = e.getMessage();
					issuccess = "N";
				}finally {
					for(LogVO vo : listVOs) {
						vo.setIssuccess(issuccess);
						vo.setError(message);
						vo.setVdef2(result);
						vo.setDr("0");
						
					}
					
					getDbService().insertVOList(listVOs);
				}
			}


			BDBarCodeParseVO<AbstractMaterialVO> voo = new BDBarCodeParseVO<AbstractMaterialVO>();
			List<BDBarCodeParseVO<AbstractMaterialVO>> listvos = new ArrayList<>();
			listvos.add(voo);


		}catch(Exception e) {
			LogVO vo = new LogVO();
			vo.setPk_id(NCLocator.getInstance().lookup(IdGenerator.class).generate());
			vo.setIssuccess("N");
			vo.setPk_group("0001A210000000000JB9");
			vo.setPk_billtypeid("dwkjxjll");
			vo.setSystem_flag("financial");
			vo.setVdef1("拉取参数、类型:"+ keyMap.get("type")+",开始日期:"+keyMap.get("begindate")+"结束日期:"+keyMap.get("enddate")+",同步频率:"+keyMap.get("synctime"));
			vo.setError("单位帐套同步:"+e.getMessage());
			getDbService().insertVO(vo);
		}
		
	}
	
	/**
	 * 获取第三方同步地址
	 * @param initCode
	 * @return
	 * @throws Exception
	 */
	public String getURL(String initCode) throws Exception{
		String url = InitParamUtils.getOrgParam("GLOBLE00000000000000",initCode)+"/pty/gla-dec/v1/voucher/voucashflows";
		getLog().info("----第三步接口请求地址:" + url);
		return url;
	}

	/**
	 * 数据库操作服务
	 * @return
	 */
	public IDBService getDbService() {
		if(dbService == null) {
			dbService = NCLocator.getInstance().lookup(IDBService.class);
		}
		return dbService;
	}

	/**
	 * 构建数据查询sql
	 * @return
	 * @throws BusinessException
	 */
	@SuppressWarnings("rawtypes")
	public String buildSQL(Map keyMap) throws BusinessException{
		StringBuilder sb = new StringBuilder();
		if(keyMap != null && !keyMap.isEmpty()) {
			sb.append("  select  ");
			sb.append("         rownum,glh.pk_voucher vou_id,glb.pk_detail vou_det_id,og.code acct_set_code,og.pk_group,oos.code agency_code, ");
			sb.append("         oos.pk_org,oos.pk_vid pk_org_v,glh.year set_year,glh.period acct_period,glh.num voucher_no,glh.num vbillcode,xjll.code cash_flow_code, ");
			sb.append("         case when glb.debitamount > 0  then glb.debitamount else glb.creditamount end cash_flow_amt,glh.prepareddate voucher_date,  ");
			sb.append("         glh.modifiedtime update_time, glh.creationtime create_time,case glh.dr when 0 then 2 else 1 end is_deleted  ");
			sb.append("    from gl_voucher glh  ");
			sb.append("    inner join gl_detail glb on glh.pk_voucher = glb.pk_voucher ");
			sb.append("    inner join org_group og on glh.pk_group = og.pk_group   ");
			sb.append("    inner join org_orgs oos on glh.pk_org = oos.pk_org ");
			sb.append("    inner join gl_docfree1 free on glb.assid =  free.assid ");
			sb.append("    inner join bd_cashflow xjll on xjll.pk_cashflow = free.F7 ");
			sb.append("  where glh.tempsaveflag = 'N' and glb.dr = 0  and glh.dr = 0  ");
			sb.append(" 	and glh.discardflag = 'N' and glh.adjustperiod <> '00' ");
			sb.append(" 	and oos.code = '"+keyMap.get("org")+"'  ");
			Object startdate = null;
			Object stopdate = null;
			Object type = keyMap.get("type");
			if("1".equals(type)) { //  [指定时间段拉取,1];[拉指定的一天,2];
				Object begindate = keyMap.get("begindate")  == null  ? ymd.format(new Date()) : keyMap.get("begindate") ;
				Object enddate = keyMap.get("enddate") == null  ? ymd.format(new Date()) : keyMap.get("enddate") ;
				startdate = begindate + " 00:00:00";
				stopdate = enddate + " 23:59:59";
			}else if("2".equals(type)) { // [拉指定的一天,2]
				Object begindate = keyMap.get("begindate") == null  ? ymd.format(new Date()) : keyMap.get("begindate") ;
				startdate = begindate + " 00:00:00";
				stopdate = begindate + " 23:59:59";
			}else { // [定时执行, ] 默认同步频率30分钟  
		        Calendar calendar = Calendar.getInstance();
		        stopdate = ymdsfm.format(calendar.getTime());//当前时间
		        Object synctime = keyMap.get("synctime"); //  同步频率
		        if(synctime ==  null ) {
			        calendar.add(Calendar.MINUTE, -30); // time 的前几分钟
		        }else {
	        		int time = Integer.parseInt(synctime.toString());
			        calendar.add(Calendar.MINUTE, -time); // time 的前几分钟
		        }
		        startdate = ymdsfm.format(calendar.getTime());
			}
			sb.append(" and glh.prepareddate between '"+startdate+"' and '"+stopdate+"' ");
			return sb.toString();
		}
		return null;
	}
	
	/**
	 * 查询需要同步的数据
	 * @throws BusinessException
	 */
	@SuppressWarnings("unchecked")
	public List<Map<String, Object>>  queryData(String sql)  throws BusinessException{
		if(sql == null) return null;
		List<Map<String, Object>> lists = (List<Map<String, Object>>)getDao().executeQuery(sql, new MapListProcessor());
		return lists == null ||  lists.isEmpty() ? null : lists;
	}
	
	/**
	 * 构建请求参数
	 * @return
	 * @throws Exception 
	 */
	public JSONArray buildParam(List<Map<String, Object>> data,List<LogVO> listVOs) throws Exception{
		if(data == null) return null;
		JSONArray jsonArray = new JSONArray();
		for(Map<String, Object> map : data) {
			JSONObject json = new JSONObject();
			json.put("CASHFLOW_ID", UUID.randomUUID().toString());  //
			json.put("VOU_ID", ToolUtils.getJudgeAttribute(map.get("vou_id"))); 
			json.put("VOU_DET_ID", ToolUtils.getJudgeAttribute(map.get("vou_det_id"))); // 区划
			json.put("MOF_DIV_CODE", super.getMOF_DIV_CODE()); 
			json.put("AGENCY_CODE", super.getUnit()); //单位代码
			json.put("SET_YEAR", ToolUtils.getJudgeAttribute(map.get("set_year"))); //会计年度
			json.put("ACCT_SET_CODE", super.getAccount()); //
			json.put("ACCT_SET_NAME", super.getACCT_SET_NAME());  // 账套名称
			json.put("AGENCY_NAME", super.getAGENCY_NAME()); // 单位名称
			json.put("ACCT_PERIOD", ToolUtils.getJudgeAttribute(map.get("acct_period"))); //
			json.put("VOUCHER_NO", ToolUtils.getJudgeAttribute(map.get("voucher_no")).toString()); // 财务负责人
			json.put("CASH_FLOW_CODE", ToolUtils.getJudgeAttribute(map.get("cash_flow_code")));
			json.put("CASH_FLOW_AMT", ToolUtils.getJudgeAttribute(map.get("cash_flow_amt")));
			json.put("CREATE_TIME", super.getYMDHMS(map.get("create_time")));
			json.put("UPDATE_TIME", super.getYMDHMS(map.get("update_time")));
			Object VOUCHER_DATE = super.getYMD(map.get("voucher_date"));
			json.put("VOUCHER_DATE", VOUCHER_DATE);
			json.put("IS_DELETED", map.get("is_deleted")); // 1已删除 2 未删除
			json.put("cf_seq",map.get("rownum")); // 现金流量顺序号
			LogVO logVO = getDbService().buildLogVO(map, json, "financial", "dwkjxjll");
			listVOs.add(logVO);
			jsonArray.add(json);
		}
		return jsonArray;
	}
	
	public BaseDAO getDao() {
		return dao == null ? new BaseDAO() : dao ;
	}

}
